package com.lfc.myframe.utils;

import android.os.SystemClock;

import com.tamsiree.rxkit.TLog;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class NtpClient {
    private static final String TAG = "NTPClient";
    private static NtpClient mNtpClient = null;
    private boolean mNtpClientState = false;
    private boolean mGetNtpAsync = false;

    private static final int ORIGINATE_TIME_OFFSET = 24;
    private static final int RECEIVE_TIME_OFFSET = 32;
    private static final int TRANSMIT_TIME_OFFSET = 40;
    private static final int NTP_PACKET_SIZE = 48;

    private static final int NTP_PORT = 123;
    private static final int NTP_MODE_CLIENT = 3;
    private static final int NTP_VERSION = 3;

    // Number of seconds between Jan 1, 1900 and Jan 1, 1970
    // 70 years plus 17 leap days
    private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;

    private NtpClient() {
        mNtpClientState = false;
    }

    public synchronized static NtpClient getInstance() {
        if (mNtpClient == null) {
            mNtpClient = new NtpClient();
        }
        return mNtpClient;
    }

    /**
     * 开启ntp获取线程
     */
    public void getNTPAsync() {
        synchronized (this) {
            if (mGetNtpAsync) {
                TLog.d(TAG, "getNTPTime: mNtpClientState is false");
                return;
            }
            mGetNtpAsync = true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!requestNtp()) {
                        try {
                            Thread.sleep(5 * 1000);
                        } catch (Exception e) {
                            TLog.d(TAG, "run: " + e.toString());
                        }
                    }
                }
            }).start();
            return;
        }
    }

    /**
     * 获取ntp获取状态
     */
    public boolean getNtpState() {
        return mNtpClientState;
    }

    private boolean requestNtp() {
        boolean ret = false;
        String[] urlList;
        String NtpUrlList = "ntp1.aliyun.com, ntp2.aliyun.com, ntp3.aliyun.com, ntp4.aliyun.com, ntp5.aliyun.com, ntp6.aliyun.com, ntp7.aliyun.com," +
                "cn.pool.ntp.org, cn.ntp.org.cn, sg.pool.ntp.org, tw.pool.ntp.org, jp.pool.ntp.org, hk.pool.ntp.org, th.pool.ntp.org," +
                "time.windows.com, time.nist.gov, time.apple.com, time.asia.apple.com, dns1.synet.edu.cn, news.neu.edu.cn, dns.sjtu.edu.cn," +
                "dns2.synet.edu.cn, ntp.glnet.edu.cn, s2g.time.edu.cn, ntp-sz.chl.la, ntp.gwadar.cn, 3.asia.pool.ntp.org";

        ///TODO:获取下发URL
  /*      try {
            String url = ConfigManager.getInstance(SessionManager.getInstance().getAppContext()).getCfg(VPSConfigs.CONFIG_NTP_SERVER_URL);
            if (url != null && url.length() != 0) {
                urlList = url.split(",", 30);
                for (String ntpUrl : urlList) {
                    ret = requestNtp(ntpUrl, 30000);
                    if (ret) {
                        TLog.d(TAG, "requestNTP: request ntp time ok : " + ntpUrl);
                        return ret;
                    }
                    try {
                        Thread.sleep(2 * 1000);
                    } catch (Exception e) {
                        TLog.e(TAG, "run: " + e.toString());
                    }
                }
            }
        } catch (Exception e) {
            TLog.e(TAG, "requestNTP error: " + e.toString());
        }*/

        try {
            urlList = NtpUrlList.split(",", 30);
            for (String ntpUrl : urlList) {
                ret = requestNtp(ntpUrl, 30000);
                if (ret) {
                    TLog.d(TAG, "requestNTP: request ntp time ok : " + ntpUrl);
                    return ret;
                }
                try {
                    Thread.sleep(2 * 1000);
                } catch (Exception e) {
                    TLog.e(TAG, "run: " + e.toString());
                }
            }
        } catch (Exception e) {
            TLog.e(TAG, "requestNTP error: " + e.toString());
        }
        return ret;
    }

    /**
     * 请求ntp
     *
     * @param host
     * @param timeout
     * @return 是否获取成功
     */
    private boolean requestNtp(String host, int timeout) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        long ntpTime = requestTime(host, timeout);
        TLog.d(TAG, "requestNtp: mNtpTime " + dateFormat.format(ntpTime));
        if (ntpTime == -1) {
            return false;
        }
        Date date = new Date();
        //对比本地时间，差距1分钟则说明没准备好
        try {
            if ((date.getTime() - ntpTime > 60 * 1000) || (date.getTime() - ntpTime < (-60 * 1000))) {
                return false;
            }
        } catch (Exception e) {
            TLog.e(TAG, "requestNtp error :" + e.toString());
        }
        mNtpClientState = true;
        return true;
    }

    /**
     * 请求ntp时间
     *
     * @param host
     * @param timeout
     * @return 成功返回获取时间 失败返回 -1
     */
    private long requestTime(String host, int timeout) {
        DatagramSocket socket = null;
        InetAddress address = null;
        long ntpTime = -1;
        try {
            address = InetAddress.getByName(host);
            socket = new DatagramSocket();
            socket.setSoTimeout(timeout);
            byte[] buffer = new byte[NTP_PACKET_SIZE];
            DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

            buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

            // get current time and write it to the request packet
            final long requestTime = System.currentTimeMillis();
            final long requestTicks = SystemClock.elapsedRealtime();
            writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);

            socket.send(request);

            // read the response
            DatagramPacket response = new DatagramPacket(buffer, buffer.length);
            socket.receive(response);
            final long responseTicks = SystemClock.elapsedRealtime();
            final long responseTime = requestTime + (responseTicks - requestTicks);

            // extract the results
            final byte leap = (byte) ((buffer[0] >> 6) & 0x3);
            final byte mode = (byte) (buffer[0] & 0x7);
            final int stratum = (int) (buffer[1] & 0xff);
            final long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
            final long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
            final long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);

            long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
            long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;
            TLog.d(TAG, "Request time form ntp server success, " + address.toString() + " ,roundTripTime: " + roundTripTime);

            ntpTime = responseTime + clockOffset;
        } catch (Exception e) {
            TLog.e(TAG, "Request time from ntp server failed ,msg: " + e.getMessage());
            return ntpTime;
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
        return ntpTime;
    }

    /**
     * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
     */
    private long read32(byte[] buffer, int offset) {
        byte b0 = buffer[offset];
        byte b1 = buffer[offset + 1];
        byte b2 = buffer[offset + 2];
        byte b3 = buffer[offset + 3];

        // convert signed bytes to unsigned values
        int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
        int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
        int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
        int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

        return ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8) + (long) i3;
    }

    /**
     * Reads the NTP time stamp at the given offset in the buffer and returns
     * it as a system time (milliseconds since January 1, 1970).
     */
    private long readTimeStamp(byte[] buffer, int offset) {
        long seconds = read32(buffer, offset);
        long fraction = read32(buffer, offset + 4);
        // Special case: zero means zero.
        if (seconds == 0 && fraction == 0) {
            return 0;
        }
        return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
    }

    /**
     * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
     * at the given offset in the buffer.
     */
    private void writeTimeStamp(byte[] buffer, int offset, long time) {
        // Special case: zero means zero.
        if (time == 0) {
            Arrays.fill(buffer, offset, offset + 8, (byte) 0x00);
            return;
        }

        long seconds = time / 1000L;
        long milliseconds = time - seconds * 1000L;
        seconds += OFFSET_1900_TO_1970;

        // write seconds in big endian format
        buffer[offset++] = (byte) (seconds >> 24);
        buffer[offset++] = (byte) (seconds >> 16);
        buffer[offset++] = (byte) (seconds >> 8);
        buffer[offset++] = (byte) (seconds >> 0);

        long fraction = milliseconds * 0x100000000L / 1000L;
        // write fraction in big endian format
        buffer[offset++] = (byte) (fraction >> 24);
        buffer[offset++] = (byte) (fraction >> 16);
        buffer[offset++] = (byte) (fraction >> 8);
        // low order bits should be random data
        buffer[offset++] = (byte) (Math.random() * 255.0);
    }

}